package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOW_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private FollowMapper followMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    /**
     * 关注或取关用户
     * @param followId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followId, Boolean isFollow) {
        // 当前用户id
        Long userId = UserHolder.getUser().getId();
        // 判断当前是关注还是取关操作
        if (BooleanUtil.isTrue(isFollow)) {
            // 关注，则添加数据库条目
            Follow follow = new Follow();
            follow.setFollowUserId(followId);
            follow.setUserId(userId);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                // 将关注信息添加到redis缓存
                stringRedisTemplate.opsForSet().add(FOLLOW_KEY + userId, followId.toString());
            }
        } else {
            // 取关，则删除
            boolean isSuccess = followMapper.deleteByUserAndFollow(followId, userId);
            if (isSuccess) {
                // 将关注信息从redis缓存删除
                stringRedisTemplate.opsForSet().remove(FOLLOW_KEY + userId, followId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 返回当前用户是否被关注
     * @param followId
     * @return
     */
    @Override
    public Result followOrNot(Long followId) {
        // 当前用户id
        Long userId = UserHolder.getUser().getId();
        // 查询是否存在对应关注条目
        //Integer count = query().eq("user_id", userId).eq("follow_user_id", followId).count();
        Double score = stringRedisTemplate.opsForZSet().score(FOLLOW_KEY + userId, followId.toString());
        return Result.ok(score != null);
    }

    /**
     * 获取共同关注
     * @param userId
     * @return
     */
    @Override
    public Result getCommonFollow(Long userId) {
        Long id = UserHolder.getUser().getId();
        // 缓存中当前用户key
        String key = FOLLOW_KEY + id;
        // 缓存中传入的用户key
        String key2 = FOLLOW_KEY + userId;
        // 集合取交际
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> commonIds = intersect.stream().map(Long::parseLong).collect(Collectors.toList());
        // 根据id查询用户信息
        List<UserDTO> userDTOS = userService.listByIds(commonIds)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 返回共同关注
        return Result.ok(userDTOS);
    }
}
